import { put, takeEvery } from "@redux-saga/core/effects";
import axios from "axios";
import { API } from "../../config";
import { GetFillterProductAction, GETFILTERPRODUCT, getFilterProductSuccess, GetProductAction, GETPRODUCTBYID, GetProductByIDAction, getProductByIDSuccess, GetProductBySearchValueSuccess, GetProductsBySearchValueAction, getProductSuccess, GET_PRODUCT, GET_PRODUCT_BY_SEARCHVALUE } from "../actions/product.action";
import { Product, ProductFilterData } from "../models/product";

export default function* productSaga() {
    yield takeEvery(GET_PRODUCT, function* (action : GetProductAction) {
        const {data} = yield axios.get<Product[]>(`${API}/products?sortBy=${action.sortBy}&order=${action.order}&limit=${action.limit}`);
        yield put(getProductSuccess(action.sortBy, data))
    })

    yield takeEvery(GET_PRODUCT_BY_SEARCHVALUE, function* (action: GetProductsBySearchValueAction) {
        const {data} = yield axios.get<Product[]>(`${API}/products/search`,{
            params:action.searchValue
        })
        yield put(GetProductBySearchValueSuccess(data))
    })

    yield takeEvery(GETFILTERPRODUCT, function* (action :GetFillterProductAction) {
        const { data } = yield axios.post<ProductFilterData>(`${API}/products/filter`,action.payload)
        yield put(getFilterProductSuccess(data, action.payload.skip))
    })
    yield takeEvery(GETPRODUCTBYID, function* (action:GetProductByIDAction) {
        const { data } = yield axios.get<Product>(`${API}/product/${action.payload}`)
        yield put(getProductByIDSuccess(data))
    })
}